package ruleengine.worker;

import static com.ruleengine.worker.runner.rule.RuleArgsField.COMPUTE_RULE_FILTER_KEY;
import static com.ruleengine.worker.runner.rule.RuleArgsField.COMPUTE_RULE_MAP_KEY;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;

import java.util.List;
import java.util.Map;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.ruleengine.util.model.Message;
import com.ruleengine.worker.model.Rule;
import com.ruleengine.worker.runner.rule.PubSubRuleRunner;
import com.ruleengine.worker.runner.rule.compute.JsonFilterRuleRunner;
import com.ruleengine.worker.runner.rule.compute.JsonMapRuleRunner;
import com.ruleengine.worker.runner.rule.destination.PluginRuleRunner;
import com.ruleengine.worker.runner.rule.other.DispatchRuleRunner;

import io.vertx.core.Vertx;

/**
 * @author lianghanwei on 2024/3/20
 */
public class MultiRuleRunnerTest extends ChainBaseTest{

    private Vertx vertx;

    @BeforeEach
    public void beforeEach() {
        vertx = Vertx.vertx();
    }

    @AfterEach
    public void afterEach() {
        vertx.close();
    }

    @Test
    public void test() throws InterruptedException {
        Rule jsonFilterRule = buildRule("jsonFilterRule", Rule.RuleType.JSON_FILTER, Map.of(COMPUTE_RULE_FILTER_KEY, DEMO_FILTER_EXPRESSION));
        Rule jsonMapRule = buildRule("jsonMapRule", Rule.RuleType.JSON_MAP, Map.of(COMPUTE_RULE_MAP_KEY, DEMO_MAP_EXPRESSION));

        DispatchRuleRunner dispatchRuleRunner = new DispatchRuleRunner(vertx, "dispatchRuleRunner", null);
        JsonFilterRuleRunner jsonFilterRuleRunner = spy(new JsonFilterRuleRunner(vertx, "jsonFilterRuleRunner", jsonFilterRule));
        JsonMapRuleRunner jsonMapRuleRunner = spy(new JsonMapRuleRunner(vertx, "jsonMapRuleRunner", jsonMapRule));
        // PluginRuleRunner pluginRuleRunner = spy(new PluginRuleRunner(vertx, "bifromqRuleRunner", null));

        dispatchRuleRunner.subscribe(jsonFilterRuleRunner);
        jsonFilterRuleRunner.subscribe(jsonMapRuleRunner);
        // jsonMapRuleRunner.subscribe(pluginRuleRunner);

        dispatchRuleRunner.write(buildMessage(0));

        List<PubSubRuleRunner<Message, Message>> spyRuleRunnerList = List.of(jsonFilterRuleRunner, jsonMapRuleRunner);

        Thread.sleep(1000);

        for (PubSubRuleRunner<Message, Message> runner : spyRuleRunnerList) {
            verify(runner).process(any(Message.class));
        }
    }
}
